//
//  DownListView.m
//  SportSocial
//
//  Created by yull on 15/1/2.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "DownListView.h"

@implementation DownListView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.titleArray = @[@"附近的人",@"场地",@"俱乐部"];
        
        self.selectView = [[UIView alloc] initWithFrame:frame];
        self.selectView.backgroundColor = Navibar_Color;
        self.selectView.layer.masksToBounds = YES;
        [self addSubview:self.selectView];
        
        self.selectViewHeight = self.selectView.height;
        
        self.buttonArray = [NSMutableArray array];
        
        CGFloat buttonHeight = CGRectGetHeight(frame)/3;
        
        for (NSInteger i = 0; i < 3; i++){
            CGRect rect = CGRectMake(0, i * buttonHeight, CGRectGetWidth(frame), buttonHeight);
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame= rect;
            button.backgroundColor = [UIColor clearColor];
            button.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
            [self.selectView addSubview:button];
            
            [button setTitle:[self.titleArray objectAtIndex:i] forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(onSelectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.buttonArray addObject:button];
        }
        
        self.height = 0.0f;
        self.selectView.height = 0.0f;
        self.hidden = YES;
    }
    return self;
}

- (void)showList
{
    self.frame = self.superview.bounds;
    
    self.hidden = NO;
    
    self.selectView.height = 0;
    
    [UIView animateWithDuration:0.3f animations:^{
        self.selectView.height = self.selectViewHeight;
    }];
}

- (void)hideList
{
    [UIView animateWithDuration:0.3f animations:^{
        self.selectView.height = 0.0f;
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (!self.hidden) {
        [self hideList];
    }
}

- (void)onSelectButtonClicked:(UIButton *)sender
{
    self.selectIndex = [self.buttonArray indexOfObject:sender];
}

- (void)setSelectIndex:(NSInteger)selectIndex
{
    NSInteger tempIndex = _selectIndex;
    
    _selectIndex = selectIndex;
    
    if (tempIndex != selectIndex) {
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
    
    for (NSInteger i = 0;i<self.buttonArray.count;i++){
        UIButton *button = [self.buttonArray objectAtIndex:i];
        if (selectIndex == i) {
            [button setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
        }else {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}
@end
